package com.ayoka.parenting.base;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;

import com.ayoka.parenting.BuildConfig;
import com.ayoka.parenting.Constants;
import com.ayoka.parenting.R;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.ui.login.LoginByVerifyCodeActivity;
import com.jincp.common.base.APPActivityManager;
import com.jincp.common.base.AppCrashException;
import com.jincp.common.base.BaseApplication;
import com.jincp.common.http.HttpProcessor;
import com.jincp.common.http.okhttp.OkHttpProcessor;
import com.jincp.common.model.ToolBarOptions;
import com.jincp.common.networkstate.NetworkStateReceiver;
import com.jincp.common.okhttp3.log.LoggerInterceptor;
import com.jincp.common.utils.AppUtils;
import com.jincp.common.utils.SharedPreferenceUtil;
import com.jincp.common.utils.ToastUtil;
import com.jincp.image.compress.ImageCompress;
import com.jincp.image.load.ImageLoader;
import com.jincp.image.load.ImageLoaderOptions;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.ticsdk.core.TICManager;
import com.tencent.ticsdk.core.impl.utils.SdkUtil;
import com.tencent.tinker.entry.ApplicationLike;
import com.tencent.tinker.lib.service.PatchResult;
import com.tinkerpatch.sdk.TinkerPatch;
import com.tinkerpatch.sdk.loader.TinkerPatchApplicationLike;
import com.tinkerpatch.sdk.tinker.callback.ResultCallBack;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 *                             _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                     佛祖保佑        永无BUG
 *                              佛曰:
 *                   写字楼里写字间，写字间里程序员；
 *                   程序人员写程序，又拿程序换酒钱。
 *                   酒醒只在网上坐，酒醉还来网下眠；
 *                   酒醉酒醒日复日，网上网下年复年。
 *                   但愿老死电脑间，不愿鞠躬老板前；
 *                   奔驰宝马贵者趣，公交自行程序员。
 *                   别人笑我忒疯癫，我笑自己命太贱；
 *                   不见满街漂亮妹，哪个归得程序员？
*/
public class AppContext extends BaseApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        AppUtils.stopWatchDog(BuildConfig.DEBUG);
        /**
         * tinker
         */
        initTinker();
        /**
         * 蒲公英
         */
        initPGY();
        /**
         * Activity的管理
         */
        registerActivityLifecycleCallbacks(APPActivityManager.getInstance());
        /**
         * crash监听
         */
        AppCrashException.getInstance().init(this);
        CrashReport.initCrashReport(this, Constants.TENCENT_BUGLY_APPID, true);
        /**
         * OkHttp网络请求
         */
        initOkHttp3();
        /**
         * 初始化网络状态监听器
         */
        initNetworkStateListener();
        /**
         * 初始化图片加载
         */
        ImageLoader.getInstance().init(this);
        ImageLoaderOptions.init(R.mipmap.icon_image_loading, R.mipmap.icon_image_load_error);
        /**
         * 初始化图片压缩
         */
        ImageCompress.getInstance().init(this);
        /**
         * 初始化返回按钮图标
         */
        ToolBarOptions.setDefaultNavigateIconResource(R.mipmap.icon_back_black);
        /**
         * 初始化TIC
         */
        initTIC();
    }

    private void initTinker() {
        if (BuildConfig.TINKER_ENABLE) {
            // 我们可以从这里获得Tinker加载过程的信息
            ApplicationLike tinkerApplicationLike = TinkerPatchApplicationLike.getTinkerPatchApplicationLike();

            // 初始化TinkerPatch SDK, 更多配置可参照API章节中的,初始化SDK
            TinkerPatch.init(tinkerApplicationLike)
                    .reflectPatchLibrary()
                    //设置收到后台回退要求时,锁屏清除补丁,默认是等主进程重启时自动清除
                    .setPatchRollbackOnScreenOff(true)
                    //设置补丁合成成功后,锁屏重启程序,默认是等应用自然重启
                    .setPatchRestartOnSrceenOff(true)
                    .setPatchResultCallback(new ResultCallBack() {
                        @Override
                        public void onPatchResult(PatchResult patchResult) {
                            SharedPreferenceUtil.putBoolean("TinkerPatch", patchResult.isSuccess);
                            Log.e("TAG", "补丁修复:" + (patchResult.isSuccess ? "成功" : "失败"));
                        }
                    });

            //向后台获取是否有补丁包更新,默认的访问间隔为3个小时，若参数为true,即每次调用都会真正的访问后台配置
            //你也可以在用户登录或者APP启动等一些关键路径，使用fetchPatchUpdate(true)强制检查更新
            TinkerPatch.with().fetchPatchUpdate(true);
        }
    }

    private void initPGY() {
    }

    //添加网络状态监听
    private void initNetworkStateListener() {
        //添加网络状态监听
        NetworkStateReceiver.registerNetworkStateReceiver(this);
    }


    // 初始化OkHttp3网络请求
    private void initOkHttp3() {
        OkHttpClient.Builder builder = OkHttpProcessor.getBuilder(true);
        // 设置token
        Interceptor mTokenInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                if (UserManager.getInstance() == null ||
                        TextUtils.isEmpty(UserManager.getInstance().auth_token)) {
                    return chain.proceed(originalRequest);
                } else {
                    Request authorised = originalRequest.newBuilder()
                            .header("Authorization", "Bearer " + UserManager.getInstance().auth_token)
                            .build();
                    return chain.proceed(authorised);
                }
            }
        };
        // 设置token拦截器
        builder.addInterceptor(mTokenInterceptor);
        // 设置logger拦截器
        builder.addInterceptor(new LoggerInterceptor(true));
        OkHttpProcessor.setOkHttpClient(builder);
        HttpProcessor.getInstance().init(this);
    }

    /**
     * 初始化TIC
     */
    private void initTIC() {
        if (UserManager.getInstance() != null && SdkUtil.isMainProcess(this)) {    // 仅在主线程初始化
            // 初始化TIC
            TICManager.getInstance().init(this, UserManager.getInstance().tim_sdk_appid);
        }
    }

    /**
     * 登出
     *
     * @param activity
     */
    public static void logout(Activity activity) {
        UserManager.setUserInformation(null);
        LoginByVerifyCodeActivity.start(activity);
        activity.finish();
    }

    // 需要重新登录
    public static void reLogin() {
        UserManager.setUserInformation(null);
        Activity currentActivity = APPActivityManager.getInstance().getTopActivity();
        if (currentActivity != null) {
            ToastUtil.getInstance().show("登录超时，请重新登录");
            logout(currentActivity);
        }
    }

    @Override
    public void onTerminate() {
        TICManager.getInstance().unInit();
        super.onTerminate();
    }
}
